<?php

/**
 * Contain functions modified from php to satisfy this project.
 *
 * @author trung
 * @access public
 *
 * @since 1.0
 * @package OWL
 * @subpackage Helper
 */

class Owl_System_Helper {

    /**
     * Copy an object.Returns a cloned copy of an object.
     *
     * Modified from php function clone().
     *
     * @since 1.0
     *
     * @param object $object The object to clone
     * @return object The cloned object
     */
    static function system_clone($object) {
        static $canclone;
        if (!is_object($object)){
            return null;
        }
        if ( !isset($canclone)){
           $canclone=version_compare(phpversion(), '5.0','>=');
        }
        return $canclone ? clone($object) : $object;
    }

    static function create_instance($class_name) {
        $instance = new $class_name;
        if (is_object($instance)) {
            return $instance;
        }
        else {
            return null;
        }
    }

    /**
     * Check whether variable is a Error.
     *
     * Looks at the object and if a Error class.
     *
     * Modified from php function: is_a
     *
     * @since 1.0
     * @static
     *
     * @param mixed $thing Check if unknown variable is Error object.
     * @return bool True, if Error. False, if not Error.
     */
    static function is_error($thing) {
        if ( is_object($thing) && is_a($thing, 'Error') )
            return true;
        return false;
    }

    /**
     * Parses a string into variables to be stored in an array.
     *
     * Modified from php function: parse_str()
     *
     * @link http://www.php.net/parse_str parse_str()
     *
     * @since 1.0
     *
     * @param string $string The string to be parsed.
     * @param array $array Variables will be stored in this array.
     */
    static function parse_str( $string, &$array ) {
            parse_str( $string, $array );
            if ( get_magic_quotes_gpc() )
                    $array = self::stripslashes( $array );
            return $array;
    }

    /**
     * Merge user defined arguments into defaults array.
     *
     * This function is used to allow for both string or array
     * to be merged into another array.
     *
     * Modify from php function array_merge()
     *
     * @since 1.0
     *
     * @param string|array $args Value to merge with $defaults
     * @param array $defaults Array that serves as the defaults.
     * @return array Merged user defined values with defaults.
     */
    static function array_merge( $args, $defaults = '' ) {
            if ( is_object( $args ) )
                    $r = get_object_vars( $args );
            elseif ( is_array( $args ) )
                    $r =& $args;
            else
                    self::parse_str( $args, $r );

            if ( is_array( $defaults ) )
                    return array_merge( $defaults, $r );
            return $r;
    }

    /**
     * Check value to find if it was serialized.
     *
     * If $data is not an string, then returned value will always be false.
     * Serialized data is always a string.
     *
     * @since 1.0
     *
     * @param mixed $data Value to check to see if was serialized.
     * @return bool False if not serialized and true if it was.
     */
    static function is_serialized( $data ) {
            // if it isn't a string, it isn't serialized
            if ( !is_string( $data ) )
                    return false;
            $data = trim( $data );
            if ( 'N;' == $data )
                    return true;
            if ( !preg_match( '/^([ad Obis]):/', $data, $badions ) )
                    return false;
            switch ( $badions[1] ) {
                    case 'a' :
                    case 'O' :
                    case 's' :
                            if ( preg_match( "/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data ) )
                                    return true;
                            break;
                    case 'b' :
                    case 'i' :
                    case 'd' :
                            if ( preg_match( "/^{$badions[1]}:[0-9.E-]+;\$/", $data ) )
                                    return true;
                            break;
            }
            return false;
    }

    /**
     * Check whether serialized data is of string type.
     *
     * @since 1.0
     *
     * @param mixed $data Serialized data
     * @return bool False if not a serialized string, true if it is.
     */
    static function is_serialized_string( $data ) {
            // if it isn't a string, it isn't a serialized string
            if ( !is_string( $data ) )
                    return false;
            $data = trim( $data );
            if ( preg_match( '/^s:[0-9]+:.*;$/s', $data ) ) // this should fetch all serialized strings
                    return true;
            return false;
    }

    /**
     * Unserialize value only if it was serialized.
     *
     * @since 1.0
     *
     * @param string $original Maybe unserialized original, if is needed.
     * @return mixed Unserialized data can be any type.
     */
    static function unserialize( $original ) {
            if ( self::is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
                    return @unserialize( $original );
            return $original;
    }

    /**
     * Serialize data, if needed.
     *
     * @since 1.0
     *
     * @param mixed $data Data that might be serialized.
     * @return mixed A scalar data
     */
    static function serialize( $data ) {
            if ( is_array( $data ) || is_object( $data ) )
                    return serialize( $data );

            if ( self::is_serialized( $data ) )
                    return serialize( $data );

            return $data;
    }


    /**
     * Navigates through an array and removes slashes from the values.
     *
     * If an array is passed, the array_map() function causes a callback to pass the
     * value back to the function. The slashes from this value will removed.
     *
     * Modify from php function stripslashes()
     *
     * @since 1.0
     *
     * @param array|string $value The array or string to be striped.
     * @return array|string Stripped array (or string in the callback).
     */
    static function stripslashes($value) {
            $value = is_array($value) ? array_map('Owl_System_Helper::stripslashes', $value) : stripslashes($value);
            return $value;
    }

    static function switch_type($object,$output = ARRAY_A){
         switch ($output) {
                case OBJECT : return $object;
                              break;
                case ARRAY_A : return get_object_vars($object);
                               break;
                case ARRAY_N : return array_values(get_object_vars($object));
                               break;
            }
    }

    static function rand( $min = 0, $max = 0 ) {
        global $rnd_value;

        $seed = UNIQUE_PHRASE.uniqid();

        // Reset $rnd_value after 14 uses
        // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
        if ( strlen($rnd_value) < 8 ) {
            $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
            $rnd_value .= sha1($rnd_value);
            $rnd_value .= sha1($rnd_value . $seed);
            $seed = md5($seed . $rnd_value);
        }

        // Take the first 8 digits for our value
        $value = substr($rnd_value, 0, 8);

        // Strip the first eight, leaving the remainder for the next call to wp_rand().
        $rnd_value = substr($rnd_value, 8);

        $value = abs(hexdec($value));

        // Reduce the value to be within the min - max range
        // 4294967295 = 0xffffffff = max random number
        if ( $max != 0 )
            $value = $min + (($max - $min + 1) * ($value / (4294967295 + 1)));

        return abs(intval($value));
    }

    static function generate_random_string($length = 12, $lower = true, $special_chars = true) {
        if ($lower) {
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        }
        else {
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        }
        if ( $special_chars )
            $chars .= '!@#$%^&*()';

        $password = '';
        for ( $i = 0; $i < $length; $i++ )
            $password .= substr($chars, self::rand(0, strlen($chars) - 1), 1);
        return $password;
    }

    static function hash($str, $salt = "", $raw_output = null) {
        return md5(md5($str).$salt, $raw_output);
    }

    static function name_encode($string) {
        return preg_replace("[\\W]","",base64_encode($string));
    }

    static function in_array($needle,$array) {
        foreach($array as $value){
            if (in_array($needle,$value)){
                return false;
            }
        }
        return true;
    }

    
}
?>